package es.bracana.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import es.bracana.domain.Clients;
import es.bracana.rep.ClientsDAO;

@Controller
@RequestMapping(value = "/")
public class ClientsController {
	
	@Autowired
	private ClientsDAO clientsDao;

	@RequestMapping(method = RequestMethod.GET)
	public String displaySortedClients(Model model) {
		model.addAttribute("newClient", new Clients());

//		 if (clientsDao != null)
//
//		 if (clientsDao.findAllOrderedByName() != null)
//		 model.addAttribute("clients", clientsDao.findAllOrderedByName());
		return "index";
	}

	@RequestMapping(method = RequestMethod.POST)
	public String registerNewMember(
			@Valid @ModelAttribute("newClient") Clients newClient,
			BindingResult result, Model model) {
		if (!result.hasErrors()) {
			clientsDao.register(newClient);
			return "redirect:/";
		} else {
			model.addAttribute("clients", clientsDao.findAllOrderedByName());
			return "index";
		}
	}

//	public ModelAndView handleRequest(HttpServletRequest request,
//			HttpServletResponse response) throws ServletException, IOException {
//
//		return new ModelAndView("index.jsp");
//	}

}
